//
//  ClubSquareForumDetailView.swift
//  77Club
//
//  Created by Apple on 2025/1/7.
//

import UIKit
import VersaPlayer
import MediaPlayer

class ClubSquareForumDetailCell: UITableViewCell {
    
    private let bannarCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let playerView = VersaPlayerView()
    private var controls = VersaPlayerControls()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(16.font_semiBold).line(0).end()
    private let contentLabel = c_make_ex(UITextView.self)
        .color("#4B4C4D").font(15.font_regular).end()
    private var imgs = [String]()
    private let pageView = c_make_ex(UIView.self)
        .bgColor("#F7F8FA".toColor.alpha(0.3)).corner(11).end()
    private let currenPage = c_make_ex(UILabel.self)
        .color(.white).font(12.font_semiBold).alignment(.right).end()
    private let tagsLabel = c_make_ex(UITextView.self)
        .color("#4B4C4D").font(15.font_regular).end()
    private let gameCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let totalPage = c_make_ex(UILabel.self)
        .color(.white.alpha(0.5)).font(9.font_semiBold).end()
    lazy var slider: VersaSeekbarSlider = {
       let makeView = VersaSeekbarSlider()
        //  最小值
        makeView.minimumValue = 0.0
        //  最大值
        makeView.maximumValue = 100.0
        //  设置默认值
//        makeView.setValue(sliderDefalutValue, animated: true)
        //  滑动条有值部分颜色
        makeView.minimumTrackTintColor = .white
        //  滑动条没有值部分颜色
        makeView.maximumTrackTintColor = .black.alpha(0.5)
        makeView.isUserInteractionEnabled = false
        makeView.setThumbImage(UIImage(), for: .normal)
        return makeView
    }()
    private let playButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_play",state: .selected).image("Dynamic_detail_pause").end()
    private let fullButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_full").end()
    private let voiceButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_aloud").image("Dynamic_detail_slience", state: .selected).end()
    private lazy var timeLabel = c_make_ex(UILabel.self)
        .color(.white).font(10.font_medium).alignment(.right).end()
    private var isFull = false
    
    var popBlock:(()->())?
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    /// 话题主页
    var toTopicDetailVC: ((_ topicId: String) -> Void)?
    /// 游戏详情
    var toGameDetailVC: ((_ gameId: String) -> Void)?
    var jumpToDetail:((_:String, _ uid: String)->())?
    var updateDataBlock:((_ model: ClubGameCommunityDetailModel)->())?
    
    private var tagsString = [ClubForumDetailModel]()
    private var tagsTapValue = [String]()
    private var imgTapValue = [String]()
    private var topicTapValue = [String]()
    private var postTapValue = [String]()
    private var contentH = 0.0
    
    var model: ClubGameCommunityDetailModel?{
        didSet{
            guard let md = model else { return }
            if md.video.count > 0 {
                bannarCollectionView.isHidden = true
                playerView.isHidden = false
                if let url = URL.init(string: md.video) {
                    let item = VersaPlayerItem(url: url)
                    playerView.set(item: item)
                }
                titleLabel.topConstraint?.constant = 215
                pageView.isHidden = true
            }else if md.image.count > 0{

                bannarCollectionView.isHidden = false
                playerView.isHidden = true
                if md.image.count > 1 {
                    pageView.isHidden = false
                    totalPage.text = "/\(md.image.count)"
                    currenPage.text = "1"
                }else{
                    pageView.isHidden = true
                }
                self.imgs = md.image
                bannarCollectionView.reloadData()
                titleLabel.topConstraint?.constant = 215
            }else{
                pageView.isHidden = true
                bannarCollectionView.isHidden = true
                playerView.isHidden = true
                titleLabel.topConstraint?.constant = 5
            }
            titleLabel.text = md.title
            
            let content = removeHTMLTags(from: md.content_h5)
            let attrString = self.createAttributedText(from: content, type: 1)
            contentLabel.attributedText = attrString
            
            let size = CGSize(width: CGFloat.screenWidth - 104.0.Scale, height: .greatestFiniteMagnitude)
            let optionsa: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
                // 使用 boundingRect 方法计算高度
            let boundingRect = contentLabel.attributedText.boundingRect(with: size, options: optionsa, context: nil)
            self.contentLabel.heightConstraint?.constant = ceil(boundingRect.height)

            tagsString.removeAll()
            var nameArr = [ClubForumDetailModel]()
            var tagsStr = [String]()
            if let games = md.games, games.count > 0 {
                for game in games {
                    let name = "[图片]" + game.name
                    tagsStr.append(name)
                    let md = ClubForumDetailModel(id: game.gid, uid: "0", title: name, type: 1)
                    nameArr.append(md)
                }
                gameCollectionView.isHidden = false
                gameCollectionView.heightConstraint?.constant = 56.0.Scale
                gameCollectionView.reloadData()
            }else{
                gameCollectionView.isHidden = true
                gameCollectionView.heightConstraint?.constant = 0
            }
            if let topics = md.subjects, topics.count > 0 {
                for topic in topics {
                    let name = "#" + topic.name
                    tagsStr.append(name)
                    let md = ClubForumDetailModel(id: topic.subject_id, uid: "0", title: name, type: 2)
                    nameArr.append(md)
                }
            }
            if let tags = md.bbss, tags.count > 0 {
                for tag in tags {
                    let name = "+" + tag.title
                    tagsStr.append(name)
                    let md = ClubForumDetailModel(id: tag.news_id, uid: tag.uid, title: name, type: 3)
                    nameArr.append(md)
                }
            }
            
            if nameArr.count > 0 {
                
                tagsLabel.isHidden = false
                tagsString = nameArr
                var tags = tagsStr.joined(separator: " ")
                if nameArr.count == 1 {
                    tags += " "
                }
                let attrStr = self.createAttributedText(from: tags, type: 2)
                tagsLabel.attributedText = attrStr
                let tagsRect = tagsLabel.attributedText.boundingRect(with: size, options: optionsa, context: nil)
                self.tagsLabel.heightConstraint?.constant = ceil(tagsRect.height)
            }else{
                
                tagsLabel.isHidden = false
                tagsLabel.heightConstraint?.constant = 0
            }
        }
    }
    

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            bannarCollectionView
            playerView
            titleLabel
            contentLabel
            pageView.subviews{
                currenPage
                totalPage
            }
            tagsLabel
            gameCollectionView
        }
        
        playerView.use(controls: controls)
        
        let bannarLayout = UICollectionViewFlowLayout()
        bannarLayout.minimumLineSpacing = 0
        bannarLayout.minimumInteritemSpacing = 0
        bannarLayout.scrollDirection = .horizontal
        
        bannarCollectionView.collectionViewLayout = bannarLayout
        bannarCollectionView.backgroundColor = .clear
        bannarCollectionView.register(ClubDynamicDetailBannarCell.self, forCellWithReuseIdentifier: ClubDynamicDetailBannarCell.description())
        bannarCollectionView.showsHorizontalScrollIndicator = false
        bannarCollectionView.delegate = self
        bannarCollectionView.dataSource = self
        bannarCollectionView.isPagingEnabled = true
        
        let gameLayout = UICollectionViewFlowLayout()
        gameLayout.minimumLineSpacing = 8
        gameLayout.minimumInteritemSpacing = 8
        gameLayout.scrollDirection = .horizontal
        
        gameCollectionView.collectionViewLayout = gameLayout
        gameCollectionView.backgroundColor = .clear
        gameCollectionView.register(ClubSquareForumDetailGamesCell.self, forCellWithReuseIdentifier: ClubSquareForumDetailGamesCell.description())
        gameCollectionView.showsHorizontalScrollIndicator = false
        gameCollectionView.delegate = self
        gameCollectionView.dataSource = self
        
        bannarCollectionView.leading(0).top(0).height(210).width(.screenWidth)
        playerView.leading(0).top(0).height(210).width(.screenWidth)
        titleLabel.leading(12).trailing(12).top(215)
        contentLabel.leading(12).trailing(12)
        contentLabel.Top == titleLabel.Bottom + 12.0.Scale
        tagsLabel.leading(12).trailing(12)
        tagsLabel.Top == contentLabel.Bottom + 4
        gameCollectionView.leading(12).trailing(12).height(56.0.Scale).bottom(12.0.Scale)
        gameCollectionView.Top == tagsLabel.Bottom + 8
                
        pageView.width(45).height(22).centerHorizontally()
        pageView.Bottom == bannarCollectionView.Bottom - 12
        totalPage.leading(22.5).centerVertically()
        currenPage.trailing(22.5).centerVertically()
        
        contentLabel.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        contentLabel.addGestureRecognizer(tapGesture)
        
        contentLabel.isEditable = false
        contentLabel.isScrollEnabled = false
        contentLabel.isUserInteractionEnabled = true
        contentLabel.backgroundColor = .clear
        contentLabel.translatesAutoresizingMaskIntoConstraints = false
        contentLabel.textContainerInset = .zero
        contentLabel.textContainer.lineFragmentPadding = 0
        
        tagsLabel.isUserInteractionEnabled = true
        let tagsTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTagsTap(_:)))
        tagsLabel.addGestureRecognizer(tagsTapGesture)
        
        tagsLabel.isEditable = false
        tagsLabel.isScrollEnabled = false
        tagsLabel.isUserInteractionEnabled = true
        tagsLabel.backgroundColor = .clear
        tagsLabel.translatesAutoresizingMaskIntoConstraints = false
        tagsLabel.textContainerInset = .zero
        tagsLabel.textContainer.lineFragmentPadding = 0
        
        playerView.backgroundColor = .black
        playerView.playbackDelegate = self
        playerView.controls?.behaviour.showingControls = true
        playerView.isHidden = true
        
        controls.subviews{
            slider
            playButton
            fullButton
            voiceButton
            timeLabel
        }
        
        playButton.leading(0).bottom(0).size(44)
        slider.leading(48).height(1.5).width(205)
        slider.CenterY == playButton.CenterY
        fullButton.trailing(12).size(24)
        fullButton.CenterY == playButton.CenterY
        voiceButton.trailing(36).size(24)
        voiceButton.CenterY == playButton.CenterY
        timeLabel.trailing(60)
        timeLabel.CenterY == playButton.CenterY
        
        playButton.addTarget(self, action: #selector(clickPlayButton), for: .touchUpInside)
        voiceButton.addTarget(self, action: #selector(clickVoiceButton), for: .touchUpInside)
        fullButton.addTarget(self, action: #selector(clickFullButton), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(stopVideoPlay), name: .stopDetailAudioPlayer, object: nil)
    }
    
    @objc private func clickGameView(){
        popBlock?()
    }
    
    @objc private func stopVideoPlay(){
        playerView.pause()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: loadData
extension ClubSquareForumDetailCell{
    
    //type: 1、内容 2、tags
    private func createAttributedText(from text: String, type: Int) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: text)
        attributedString.addAttribute(.foregroundColor, value: "#47494D".toColor, range: NSRange(location: 0, length: attributedString.length))
        attributedString.addAttribute(.font, value: 15.font_regular!, range: NSRange(location: 0, length: attributedString.length))
        
        let nsText = text as NSString
        var count = 0
        var offset = 0 // 偏移量
        var index = 0  // 用于生成唯一的 actionType 标识
        
        // 正则匹配 [图片] 和 #标签
        let hashtagRegex = try! NSRegularExpression(pattern: "#[^\\s]+", options: [])
        let imageTextRegex = try! NSRegularExpression(pattern: "\\[图片\\](\\S+?) ", options: [])
        let postTagRegex = try! NSRegularExpression(pattern: "\\+\\S+", options: [])
        
        // **1. 优先处理 #标签**
        let hashtagMatches = hashtagRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in hashtagMatches {
            let matchRange = match.range(at: 0)
            guard matchRange.location != NSNotFound else { continue }
            
            let hashtagRange = NSRange(location: matchRange.location + offset, length: matchRange.length)
            guard hashtagRange.location >= 0,
                  hashtagRange.location + hashtagRange.length <= attributedString.length else { continue }
            
            if var substring = attributedString.attributedSubstring(from: hashtagRange).string as String? {
                if let subjects = model?.subjects {
                    if substring.hasPrefix("#") {
                        substring.removeFirst()
                    }
                    if subjects.contains(where: { $0.name == substring }) {
                        index += 1
                        attributedString.addAttribute(.foregroundColor, value: "#E57617".toColor, range: hashtagRange) // 设置颜色
                        if type == 1 {
                            self.topicTapValue.append("hashtag_\(index)")
                            attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "hashtag_\(index)", range: hashtagRange)
                        }else{
                            self.tagsTapValue.append("tags_\(hashtagRange)")
                            attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "tags_\(hashtagRange)", range: hashtagRange)
                        }
                    }
                }
            }
        }
        
        // **2. 优先处理 +标签**
        let posttagMatches = postTagRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in posttagMatches {
            let matchRange = match.range(at: 0)
            guard matchRange.location != NSNotFound else { continue }
            
            let posttagRange = NSRange(location: matchRange.location + offset, length: matchRange.length)
            guard posttagRange.location >= 0,
                  posttagRange.location + posttagRange.length <= attributedString.length else { continue }
            if var substring = attributedString.attributedSubstring(from: posttagRange).string as String? {
                if let bbss = model?.bbss {
                    if substring.hasPrefix("+") {
                        substring.removeFirst()
                    }
                    if bbss.contains(where: { $0.title == substring && $0.news_id != "0" }) {
                        index += 1
                        attributedString.addAttribute(.foregroundColor, value: "#1280E5".toColor, range: posttagRange) // 设置颜色
                        if type == 1 {
                            self.postTapValue.append("posttag_\(index)")
                            attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "posttag_\(index)", range: posttagRange)
                        }else{
                            self.tagsTapValue.append("tags_\(posttagRange)")
                            attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "tags_\(posttagRange)", range: posttagRange)
                        }
                    }
                }
            }
        }
        
        // **3. 处理 [图片]**
        let imageTextMatches = imageTextRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in imageTextMatches {
            let fullMatchRange = NSRange(location: match.range(at: 0).location + offset, length: match.range(at: 0).length)
            let textRange = NSRange(location: match.range(at: 1).location + offset, length: match.range(at: 1).length)
            
            // 替换 [图片] 为图片
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: "Square_gameTag") // 替换为图片
            attachment.bounds = CGRect(x: 0, y: -7, width: 20, height: 20)
            let imageString = NSAttributedString(attachment: attachment)
            
            attributedString.replaceCharacters(in: NSRange(location: fullMatchRange.location, length: "[图片]".count), with: imageString)
            offset += imageString.length - "[图片]".count // 更新偏移量
            
            // 设置图片后面的文字颜色
            let updatedTextRange = NSRange(location: textRange.location + offset + (3 * count), length: textRange.length)
            if updatedTextRange.location + updatedTextRange.length <= attributedString.length {
                index += 1
                attributedString.addAttribute(.foregroundColor, value: "#3D9399".toColor, range: updatedTextRange)
                if type == 1 {
                    self.imgTapValue.append("imageText_\(index)")
                    attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "imageText_\(index)", range: updatedTextRange)
                }else{
                    self.tagsTapValue.append("tags_\(updatedTextRange)")
                    attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "tags_\(updatedTextRange)", range: updatedTextRange)
                }
            }
            count += 1
        }
        
        return attributedString
    }
    
    func removeHTMLTags(from text: String) -> String {
        let regexPattern = "<[^>]+>" // 匹配所有 HTML 标签
        let regex = try! NSRegularExpression(pattern: regexPattern, options: [])
        let range = NSRange(location: 0, length: text.utf16.count)
        let cleanedText = regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "")
        return cleanedText
    }
}


//MARK: action
extension ClubSquareForumDetailCell: VersaPlayerPlaybackDelegate {
    
    @objc private func clickPlayButton(){
        self.playButton.isSelected = !self.playButton.isSelected
        if self.playButton.isSelected {
            playerView.pause()
        }else{
            playerView.play()
        }
    }
    
    @objc private func clickFullButton(){
        
        self.isFull = !self.isFull
        self.playerView.setFullscreen(enabled: self.isFull)
    }
    
    @objc private func clickVoiceButton(){
        self.voiceButton.isSelected = !self.voiceButton.isSelected
        if self.voiceButton.isSelected {
            playerView.player.volume = 0
        }else{
            playerView.player.volume = 1
        }
    }
    
    func timeDidChange(player: VersaPlayer, to time: CMTime) {
        
        let seconds = CMTimeGetSeconds(time)
        let endTime = CMTimeGetSeconds(player.endTime())
        
        let currentT = CMTimeGetSeconds(time)
        let currentTStr = Int(currentT).toPlayTimeStr()
        let endTStr = Int(endTime).toPlayTimeStr()
        timeLabel.text = currentTStr + "/" + endTStr
        let totalT = self.playerView.player.endTime().seconds
        let progress = currentT / totalT * 100.0
        slider.value = Float(progress)
        
        if Int(seconds) == Int(endTime) {
            player.pause()
            let time:CMTime = CMTimeMakeWithSeconds(0.1, preferredTimescale: 1 * Int32(NSEC_PER_SEC))
            player.seek(to: time, toleranceBefore: CMTime.zero, toleranceAfter:CMTime.zero)
            player.play()
        }
        
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: contentLabel)
        
        // 获取点击位置的字符索引
        if let position = contentLabel.closestPosition(to: location) {
            let characterIndex = contentLabel.offset(from: contentLabel.beginningOfDocument, to: position)
            
            // 确保 characterIndex 不超过富文本长度
            if characterIndex < contentLabel.attributedText.length {
                
                // 获取点击位置的属性
                let attributes = contentLabel.attributedText.attributes(at: characterIndex, effectiveRange: nil)
                
                // 检查是否存在 "actionType" 属性
                if let actionType = attributes[NSAttributedString.Key("actionType")] as? String {
                    if actionType.hasPrefix("hashtag_") {
                        print("The string starts with 'hashtag_'")
                        if let index = self.topicTapValue.firstIndex(of: actionType) {
                            if let gamesId = model?.subjects?[index].subject_id {
                                self.toTopicDetailVC?(gamesId)
                            }
                        }
                    }else if actionType.hasPrefix("imageText_")  {
                        // 执行对应的操作
                        if let index = self.imgTapValue.firstIndex(of: actionType) {
                            if let gamesId = model?.games?[index].gid {
                                self.toGameDetailVC?(gamesId)
                            }
                        }
                    }else if actionType.hasPrefix("posttag_")  {
                        // 执行对应的操作
                        if let index = self.postTapValue.firstIndex(of: actionType) {
                            if let postM = model?.bbss?[index] {
                                let gamesId = postM.news_id
                                let uid = postM.uid
                                self.jumpToDetail?(gamesId,uid)
                            }
                        }
                    }
                }
            }
        }
    }
    
    @objc func handleTagsTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: tagsLabel)
        
        // 获取点击位置的字符索引
        if let position = tagsLabel.closestPosition(to: location) {
            let characterIndex = tagsLabel.offset(from: tagsLabel.beginningOfDocument, to: position)
            
            // 确保 characterIndex 不超过富文本长度
            if characterIndex < tagsLabel.attributedText.length {
                
                // 获取点击位置的属性
                let attributes = tagsLabel.attributedText.attributes(at: characterIndex, effectiveRange: nil)
                
                // 检查是否存在 "actionType" 属性
                if let actionType = attributes[NSAttributedString.Key("actionType")] as? String {
                    if actionType.hasPrefix("tags_") {
                        if let actionIndex = getClickedActionIndex(attributedText: tagsLabel.attributedText, clickIndex: characterIndex) {
                            let md = tagsString[actionIndex]
                            if md.type == 1 {
                                toGameDetailVC?(md.id)
                            }else if md.type == 2 {
                                toTopicDetailVC?(md.id)
                            }else if md.type == 3 {
                                jumpToDetail?(md.id,md.uid)
                            }
                        } else {
                            print("未点击任何可交互区域")
                        }
                    }
                }
            }
        }
    }
    
    private func getClickedActionIndex(attributedText: NSAttributedString, clickIndex: Int) -> Int? {
        // 保存所有点击事件的范围
        var actionRanges: [NSRange] = []
        
        // 遍历 NSAttributedString，提取带有 "actionType" 属性的 NSRange
        attributedText.enumerateAttribute(NSAttributedString.Key("actionType"), in: NSRange(location: 0, length: attributedText.length), options: []) { value, range, _ in
            if value != nil {
                actionRanges.append(range)
            }
        }
        
        // 遍历所有范围，找到点击的范围
        for (index, range) in actionRanges.enumerated() {
            if range.contains(clickIndex) {
                return index // 返回第几个点击事件
            }
        }
        
        // 如果不在任何范围内，返回 nil
        return nil
    }
}

//MARK: action
extension ClubSquareForumDetailCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if bannarCollectionView == collectionView {
            return imgs.count
        }else if gameCollectionView == collectionView {
            return model?.games?.count ?? 0
        }else{
            return tagsString.count
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if bannarCollectionView == collectionView {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubDynamicDetailBannarCell.description(), for: indexPath) as? ClubDynamicDetailBannarCell else { return UICollectionViewCell() }
            cell.imgUrl = imgs[indexPath.row]
            return cell
        }else {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubSquareForumDetailGamesCell.description(), for: indexPath) as? ClubSquareForumDetailGamesCell else { return UICollectionViewCell() }
            cell.gameModel = model?.games?[indexPath.row]
            return cell
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if collectionView == bannarCollectionView {
            if model?.image.count ?? 0 > 0 {
                didSelectImage?(indexPath.row,model?.image ?? [])
            }
        }else if collectionView == gameCollectionView {
            guard let games = model?.games, games.count > 0 else { return }
            toGameDetailVC?(games[indexPath.row].gid)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if collectionView == bannarCollectionView {
            return CGSize(width: .screenWidth, height: 210)
        } else {

            if let games = model?.games {
                if games.count == 1 {
                    return CGSize(width: .screenWidth - 24.0.Scale, height: 56.0.Scale)
                }else{
                    return CGSize(width: 250.0.Scale, height: 56.0.Scale)
                }
            }else{
                return .zero
            }
        }
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        guard let collectionView = scrollView as? UICollectionView, collectionView == bannarCollectionView else { return }
            let visibleCells = collectionView.visibleCells
            for cell in visibleCells {
                // 获取 cell 在 CollectionView 中的位置
                if let indexPath = collectionView.indexPath(for: cell) {
                    // 判断该 cell 是否完全可见
                    let cellFrame = collectionView.layoutAttributesForItem(at: indexPath)?.frame ?? .zero
                    let cellVisibleRect = collectionView.bounds.intersection(cellFrame)

                    if cellVisibleRect == cellFrame {
                        self.currenPage.text = "\(indexPath.row + 1)"
                    }
                }
            }
    }
}


class ClubSquareForumDetailGamesCell: UICollectionViewCell {
    
    private let gameView = c_make_ex(UIView.self)
        .corner(8.0.Scale).bgColor("#4B4C4D").end()
    private let gameImageV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(8.0.Scale).end()
    private let gameNameLabel = c_make_ex(UILabel.self)
        .color(.white).font(12.font_semiBold).end()
    private var gameSubLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.85)).font(10.font_medium).end()
    
    var gameModel: DynamicGamesModel?{
        didSet{
            guard let md = gameModel else { return }
            gameImageV.loadImage(url: md.icon)
            gameNameLabel.text = md.name
            let tagStr = md.biaoqian.replacingOccurrences(of: ",", with: " · ")
            let subStr = String(md.point) + " · " + tagStr
            gameSubLabel.text = subStr
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            gameView.subviews{
                gameImageV
                gameNameLabel
                gameSubLabel
            }
        }
        
        gameView.leading(0).trailing(0).height(56.0.Scale).top(0)
        gameImageV.leading(12.0.Scale).size(32.0.Scale).centerVertically()
        gameNameLabel.top(11.0.Scale).leading(56.0.Scale)
        gameSubLabel.leading(56.0.Scale).trailing(12.0.Scale).height(16).top(28.0.Scale)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
